package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * WebFilter注解: 过滤器注解,指定过滤器的作用范围[拦截的路径PATH];
 * filterName参数: 过滤器的名称;
 * urlPatterns参数: 拦截的路径PATH;
 * 过滤器中通配符使用一个星号*,比如: /v1/vehicle/*
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    /**
     * 初始化方法
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器初始化...");
    }

    /**
     * 核心的过滤方法: 用户登录状态校验,网站限流,日志记录,性能监控...
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录状态校验的过滤器...");
        // 1.类型转换;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 2.获取会话HttpSession;
        HttpSession session = request.getSession();
        // 3.获取用户标识
        UserVO userVO = (UserVO) session.getAttribute("user");
        // 4.判断
        if (userVO != null){//登录状态没问题
            /*
                是否放行的标准:是否有改行代码 filterChain.doFilter(request, response);
                如果有该行代码: 表示放行;
                如果没有该行代码: 表示不放行;
             */
            filterChain.doFilter(request, response);
        } else{
            response.sendRedirect("/login.html");
        }
    }

    /**
     * 销毁方法
     */
    @Override
    public void destroy() {
        log.debug("过滤器销毁...");
    }
}
